package com.zg.scf.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.dao.BaseEntity;
import com.zg.common.core.dao.scf.ImgConditionDao;
import com.zg.common.core.dao.scf.entity.Company;
import com.zg.common.core.dao.scf.entity.ImgCategory;
import com.zg.common.core.dao.scf.entity.ImgCondition;
import com.zg.common.core.dao.scf.entity.ImgConditionScore;
import com.zg.common.core.dao.system.SysDict;
import com.zg.common.core.dao.system.SysDictDao;
import com.zg.common.core.service.PageBaseService;
import com.zg.scf.domain.vo.ImgConfigVo;
import com.zg.scf.domain.vo.ImgCategoryVo;
import com.zg.scf.domain.vo.ImgConditionVo;
import com.zg.scf.enm.DirectionEnum;
import com.zg.scf.service.CompanyService;
import com.zg.scf.service.ImgCategoryService;
import com.zg.scf.service.ImgConditionScoreService;
import com.zg.scf.service.ImgConditionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>Description: </p>
 *
 * @author zhanfeng.liang
 * @since 2025/5/22 10:47
 */



@Service
@Slf4j
public class ImgConditionServiceImpl extends PageBaseService<ImgCondition, ImgConditionDao> implements ImgConditionService {

    @Resource
    private CompanyService companyService;

    @Resource
    private ImgConditionScoreService imgConditionScoreService;


    @Override
    public void removeByCategoryIds(List<Long> ids) {
        LambdaQueryWrapper<ImgCondition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ImgCondition::getCategoryId, ids);
        baseDao.remove(queryWrapper);
    }

    @Override
    public List<ImgCondition> listByCategoryId(Long id) {
       ImgCondition imgCondition = new ImgCondition();
       imgCondition.setCategoryId(id);
       return list(imgCondition);
    }



//    @Resource
//    private ImgCategoryService imgCategoryService;
//
//    @Resource
//    private SysDictDao sysDictDao;
//
//    @Override
//    public List<ImgConfigVo> list(){
//        List<ImgCategory> categories = imgCategoryService.list();
//        ImgCondition imgCondition = new ImgCondition();
//        imgCondition.setCategoryIds(categories.stream().map(BaseEntity::getId).collect(Collectors.toList()));
//        List<ImgCondition> conditions = list(imgCondition);
//        List<String> sources = conditions.stream().map(ImgCondition::getSource).collect(Collectors.toList());
//        List<SysDict> pDictList =sysDictDao.listByCodes(sources);
//        List<Long> pIds = pDictList.stream().map(BaseEntity::getId).collect(Collectors.toList());
//        // 查询子级字典项
//        List<SysDict> cDictList = sysDictDao.listByPid(pIds);
//
//        // 按父级字典项ID分组子级字典项
//        Map<Long, List<SysDict>> dictMap = cDictList.stream()
//                .collect(Collectors.groupingBy(SysDict::getPid));
//
//        // 将分类按ID映射，便于后续查找
//        Map<Long, ImgCategory> categoryMap = categories.stream()
//                .collect(Collectors.toMap(ImgCategory::getId, category -> category));
//
//        // 将条件按分类ID分组
//        Map<Long, List<ImgCondition>> conditionMap = conditions.stream()
//                .collect(Collectors.groupingBy(ImgCondition::getCategoryId));
//
//        List<ImgCategory> pCategoryList = categories.stream().filter(t->t.getPid().equals(0L)).collect(Collectors.toList());
//        List<ImgCategory> allSubCategoryList = categories.stream().filter(t->!t.getPid().equals(0L)).collect(Collectors.toList());
//
//        Map<Long,List<ImgCategory>> allSubCategoryMap = allSubCategoryList.stream().collect(Collectors.groupingBy(ImgCategory::getPid));
//        ImgConfigVo pInfoVo = new ImgConfigVo();
//        List<ImgCategoryVo> pCategoryVoList = new ArrayList<>();
//        // 组装最终结果
//
//        for(ImgCategory pCategory : pCategoryList){
//            ImgCategoryVo  pCategoryVo = new ImgCategoryVo();
//            BeanUtils.copyProperties(pCategory, pCategoryVo);
//
//            List<ImgCategory>  subCategoryList =allSubCategoryMap.getOrDefault(pCategory.getId(), new ArrayList<>());
//            for (ImgCategory category : subCategoryList) {
//                ImgCategoryVo categoryVo = new ImgCategoryVo();
//
//                BeanUtils.copyProperties(category, categoryVo);
//
//                // 获取该分类下的所有条件
//                List<ImgCondition> categoryConditions = conditionMap.getOrDefault(category.getId(), new ArrayList<>());
//                List<ImgConditionVo> conditionVos = categoryConditions.stream().map(condition -> {
//                    ImgConditionVo conditionVo = new ImgConditionVo();
//                    BeanUtils.copyProperties(condition, conditionVo);
//
//                    // 设置每个condition的dictList（子字典项）
////                    String source = condition.getSource();
////                    List<SysDict> relatedDicts = dictMap.getOrDefault(
////                            pDictList.stream().filter(dict -> dict.getCode().equals(source)).findFirst().orElse(new SysDict()).getId(),
////                            new ArrayList<>());
//                    //conditionVo.setDictList(relatedDicts);
//
//                    return conditionVo;
//                }).collect(Collectors.toList());
//                categoryVo.setConditions(conditionVos);
//                infoVos.add(infoVo);
//            }
//            pCategoryVoList.add(pCategoryVo);
//        }
//
//        return result;
//    }

    /**
     * 行业分类逻辑处理
     */
//   public ImgConditionScore industryType(ImgCategory subCategory,List<ImgCondition> imgConditionList,Long companyId,Long targetCompanyId){
//       Company company = companyService.getById(targetCompanyId);
//       BigDecimal score = BigDecimal.ZERO;
//       for(int i=0;i<imgConditionList.size();i++){
//           ImgCondition imgCondition = imgConditionList.get(i);
//           if(company.getIndustryType().equals(imgCondition.getItem())){
//                score = score.add(imgCondition.getValue());
//           }
//       }
//       ImgCondition imgCondition = imgConditionList.stream().filter(t->t.getItem().equals("其它")).collect(Collectors.toList()).get(0);
//       if(score.equals(BigDecimal.ZERO)){
//           score = score.add(imgCondition.getValue());
//       }
//       if(score.compareTo(subCategory.getMax()) > 0){
//            score = subCategory.getMax();
//       }
//       return imgConditionScoreService.add(subCategory.getId(), companyId, targetCompanyId, score);
//   }

    /**
     * 字典
     */
    public ImgConditionScore computeDic(ImgConfigVo imgConfig, ImgCategoryVo pImgCategory, ImgCategoryVo subImgCategory,String value){
        BigDecimal initScore = BigDecimal.ZERO;
        Boolean flag = false;
        for(int i=0;i<subImgCategory.getConditionList().size();i++){
            ImgConditionVo imgCondition = subImgCategory.getConditionList().get(i);
            if(imgCondition.getItem().equals(value)){
                if(imgCondition.getDirection().equals(DirectionEnum.POSITIVE.getValue())){
                    initScore = initScore.add(imgCondition.getValue());
                    flag = true;
                }else{
                    initScore = initScore.subtract(imgCondition.getValue());
                    flag = true;
                }
            }

        }
        List<ImgConditionVo> deaultList = subImgCategory.getConditionList().stream().filter(t->t.getItem().equals("其它")).collect(Collectors.toList());
        if(deaultList.size()>0){
            ImgConditionVo imgCondition = deaultList.get(0);
            if(!flag){
                if(imgCondition.getDirection().equals(DirectionEnum.POSITIVE.getValue())){
                    initScore = initScore.add(imgCondition.getValue());
                }else{
                    initScore = initScore.subtract(imgCondition.getValue());
                }
            }
        }

        return imgConditionScoreService.add(subImgCategory.getId(), imgConfig.getCompanyId(), imgConfig.getTargetCompanyId(), initScore);
    }

    public ImgConditionScore computeTimes(ImgConfigVo imgConfig, ImgCategoryVo pImgCategory, ImgCategoryVo subImgCategory,Integer times){
        BigDecimal initScore = BigDecimal.ZERO;
        List<ImgConditionVo> imgConditionList = subImgCategory.getConditionList().stream().sorted((t1, t2) -> genNumber(t1.getItem()).compareTo(genNumber(t2.getItem()))).collect(Collectors.toList());
        for(int i=0;i<imgConditionList.size();i++){
            ImgConditionVo imgCondition = imgConditionList.get(i);
            if(times>genNumber(imgCondition.getItem())){
                if(imgCondition.getDirection().equals(DirectionEnum.POSITIVE.getValue())){
                    initScore = initScore.add(imgCondition.getValue());
                }else{
                    initScore = initScore.subtract(imgCondition.getValue());
                }
                break;
            }
        }

        return imgConditionScoreService.add(subImgCategory.getId(), imgConfig.getCompanyId(), imgConfig.getTargetCompanyId(), initScore);
    }

    private Integer genNumber(String s){
        String result = s.replaceAll("[^0-9]", "");
        return Integer.valueOf(result);
    }
}
